#include "metadatadialog.h"
#include "resource.h"
#include "util.h"

MetaDataDialog::MetaDataDialog()
	: Dialog( MAKEINTRESOURCE( IDD_DIALOG_METADATA ) )
{
	_collection = NULL;
	_imageNum = 0;
}

Collection* MetaDataDialog::collection() const
{
	return _collection;
}

void MetaDataDialog::setCollection( Collection *c )
{
	_collection = c;
}

int MetaDataDialog::imageNum() const
{
	return _imageNum;
}

void MetaDataDialog::setImageNum( int imageNum )
{
	assert( imageNum >= 0 ); //May not be negative

	_imageNum = imageNum;
}

BOOL MetaDataDialog::handleMessage( UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	switch( uMsg )
	{
	case WM_INITDIALOG:
		{
			//Set the text of the edit control.
			wchar_t *xml;
			xmlChar *utf8;

			utf8 = _collection->metaData( _imageNum );
			if( utf8 )
			{
				xml = util::utf8ToWcs( (const char*) utf8 );
				delete[] utf8;
				if( xml )
				{
					SetDlgItemText( hWnd(), IDC_EDIT_XML, xml );
					delete[] xml;
				}
				else
				{
					//The UTF-8 string could not be converted to a wide character string.
					MessageBox(
						NULL,
						L"Error converting character data",
						L"Message",
						MB_OK | MB_ICONEXCLAMATION
						);
				}
			}
		}
		break;
	case WM_COMMAND:
		switch( LOWORD( wParam ) )
		{
		case IDOK:
			{
				//Read the edit control (and convert this to UTF8).
				wchar_t *xml;
				xmlChar *utf8;

				//xmlLength is the number of characters in the edit box.
				HWND hWndCtrl = GetDlgItem( hWnd(), IDC_EDIT_XML );
				LRESULT xmlLength = SendMessage( hWndCtrl, WM_GETTEXTLENGTH, (WPARAM) 0, (LPARAM) 0 );
				xml = new wchar_t[ xmlLength + 1 ];

				GetDlgItemText( hWnd(), IDC_EDIT_XML, xml, xmlLength+1 );
				utf8 = (xmlChar*) util::wcsToUtf8( xml );
				delete[] xml;
				if( utf8 )
				{
					_collection->setMetaData( _imageNum, utf8 );
					delete[] utf8;
				}
				else
				{
					//The wide character string could not be converted to UTF-8.
					MessageBox(
						NULL,
						L"Error converting character input",
						L"Message",
						MB_OK | MB_ICONEXCLAMATION
						);
				}
			}
		case IDCANCEL:
			EndDialog( hWnd(), LOWORD( wParam ) );

			//Return TRUE because the dialog should not handle any more messages.
			return TRUE;
		}
		break;
	}
	//This return value will execute the normal operations (as defined in win32) for
	//the message.
	return FALSE;
}
